﻿using System;
using System.Collections.Generic;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.Extensions.Configuration;

namespace JWTTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            //var config = new ConfigurationBuilder()
            //   .AddCommandLine(args)
            //   .Build();

            //var ip = config["ip"];
            //var port = config["port"];

            //Console.WriteLine($"ip:{ip}-port:{port}");


            #region ===加密===

            //var payload = new Dictionary<string, object>
            //{
            //    { "UserId", 1639 },
            //    { "UserName", "ClueeZhuo" },
            //    { "exp",(DateTime.UtcNow.AddSeconds(60)-new DateTime(1970,1,1)).TotalSeconds}
            //};
            //var secret = "GQDst322332OuXasfdasfda@0uFiwDVk";//不要泄露

            //IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            //IJsonSerializer serializer = new JsonNetSerializer();
            //IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            //IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            //var token = encoder.Encode(payload, secret);
            //Console.WriteLine(token);

            #endregion

            #region ===解密===

            var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjE2MzksIlVzZXJOYW1lIjoiQ2x1ZWVaaHVvIiwiZXhwIjoxNTMwMzk4MDI2Ljg4NTcwMzF9.oddnnNbaQ_zWG80Nk8vKx4ZnbYAnvbtpt4dOltsEaog";

            var secret = "GQDst322332OuXasfdasfda@0uFiwDVk";//不要泄露

            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

                //不启用签名校验
                //var json = decoder.Decode(token);

                //启用签名校验
                var json = decoder.Decode(token, secret, verify: true);
                Console.WriteLine(json);
            }
            catch (FormatException)
            {
                Console.WriteLine("Token format invalid");
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }

            #endregion

            Console.ReadKey();
        }
    }
}
